package com.smforj.ssm.modules.api.controller;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.smforj.ssm.encrypt.md5.MD5;
import com.smforj.ssm.frame.core.enums.RouterMapping;
import com.smforj.ssm.frame.core.plugin.ECachePlugin;
import com.smforj.ssm.frame.core.web.controller.BaseControllerSupportImpl;
import com.smforj.ssm.frame.core.web.domain.DataResult;
import com.smforj.ssm.frame.core.web.domain.DataResult.DataStatus;
import com.smforj.ssm.modules.lib.service.EditingLogService;
import com.smforj.ssm.modules.lib.service.LibraryService;
import com.smforj.ssm.modules.lib.constant.RecordType;
import com.smforj.ssm.modules.lib.domain.CheckInResponse;
import com.smforj.ssm.modules.lib.domain.CheckOutResponse;
import com.smforj.ssm.modules.lib.domain.EditingLog;
import com.smforj.ssm.modules.lib.domain.EditingRequest;
import com.smforj.ssm.modules.lib.domain.ItemResponse;
import com.smforj.ssm.modules.lib.domain.LibraryRequest;
import com.smforj.ssm.modules.lib.domain.PatronResponse;
import com.smforj.ssm.modules.lib.domain.SysBook;
import com.smforj.ssm.modules.lib.domain.SysReader;
import com.smforj.ssm.modules.lib.domain.vo.SysBookVo;
import com.smforj.ssm.modules.lib.service.BookInfoService;
import com.smforj.ssm.modules.lib.service.SysRecordService;
import com.smforj.ssm.modules.sys.domain.SysUser;
import com.smforj.ssm.modules.sys.service.SysReaderService;
import com.smforj.ssm.modules.sys.service.SysUserService;

/**
 * .
 * 馆员工作站接口API
 *
 * @author jadeshi
 * creatDate 2017/12/29 15:06
 * className RWorkStationController.java
 * package com.smforj.ssm.restful.web.controller
 * 
 * 
 * 添加了安全检验
 * ECachePlugin 缓存
 * 
 * 该对象的方法事务上有问题，其他需要修改
 * 
 * 2018-05 Aaron
 * 
 **/
@RouterMapping("")
@Controller
@RequestMapping("/library/api/editing")
public class WorkStationController extends BaseControllerSupportImpl {

    /**
     * .
     */
    private Logger logger = Logger.getLogger("WorkStationController");

    /**
     * .
     */
    @Autowired
    @Qualifier("sysBookInfoService")
    private BookInfoService bookInfoService;
    /**
     * .
     */
    @Autowired
    @Qualifier("editingLogService")
    private EditingLogService editingLogService;
    /**
     * .
     */
    @Autowired
    @Qualifier("eslibraryService")
    private LibraryService libraryService; 
    /**
     * .
     */
    @Autowired
    @Qualifier("sysReaderService")
    private SysReaderService sysReaderService;
    /**
     * .
     */
    @Autowired
    private SysRecordService sysRecordService;
    
    @Autowired
    private SysUserService sysUserService;
    
    /****
     * 客户端与服务器登陆接口,token未使用
     * @param request 登陆请求
     * @return 登陆结果
     * @date 2017-6-30 下午2:26:29
     */
    @RequestMapping(value = {"/login"}, method = RequestMethod.POST,
            consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public DataResult<SysUser> login(@RequestBody LibraryRequest<String> request) {
        if (logger.isDebugEnabled()) {
        	logger.debug("login reader id:  " + request.getSzUserId());
        } 
        //返回读者信息
        DataResult<SysUser> result = new DataResult<SysUser>();
        SysUser user = ECachePlugin.get(request.getSzUserId());
        if(user == null)
        { 
        	//查询用户并获取用户角色信息
			user = sysUserService.getUser(request.getSzUserId(), request.getSzUserPWD());
	        if(user != null)
	        {
	        	ECachePlugin.put(user.getUserName(), user);
	        	result.addOK("", user);
	        }else
	        {
	        	result.addError("用户名或密码错误");
	        } 
        }else
        {
            if (logger.isDebugEnabled()) {
            	logger.debug("ECachePlugin get id:  " + request.getSzUserId()+"  request.getSzUserPWD(): "+request.getSzUserPWD()+" user.getPassword(): "+user.getPassword());
            }
        	if(MD5.getMd5(request.getSzUserPWD()).equals(user.getPassword()))
        		result.addOK("", user); 
        	else
        		result.addError("密码错误");
        }
        //前期为显示信息，后期将删除
        return result;
    }  

    /**
     * .
     * 上传数据测试
     *
     * @param str str
     * @return 采编信息
     * @date 2016-8-11 下午2:03:45
     */
    @RequestMapping(value = {"/datatest"}, method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public DataResult<EditingRequest> doUploadEditingDataTest(String str) {
    	if(logger.isDebugEnabled())
    		logger.debug("WorkStationController doUploadEditingDataTest");
        EditingRequest book = new EditingRequest();
        book.setSzUserId(str);
        List<SysBook> list = new ArrayList<SysBook>();
        list.add(new SysBook());
        book.setBooks(list);
        return new DataResult<EditingRequest>(DataStatus.OK, "", book);
    }


    /*****
     * 批量转换读者信息(将图书管理软件中的读者与实际卡号进行关联)
     * @param request
     * @return
     * @date 2018年5月19日 下午4:55:12
     */
    @RequestMapping(value = {"/reader"}, method = RequestMethod.POST,
            consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public DataResult<List<PatronResponse>> TranferReader(@RequestBody LibraryRequest<List<SysReader>> request)
    {
    	if(logger.isDebugEnabled())
    		logger.debug("WorkStationController TranferReader"); 
    	DataResult<List<PatronResponse>> result = new DataResult<List<PatronResponse>>();
    	result.addOK("", libraryService.doTransferReader(request));
    	return result;
    }
    /**
     * .
     * 上传采编信息,已经采编过的将进行更新，
     * 该方法会自动更新图书其他信息(如果图书信息不存在则不进行更新图书其他信息)
     *
     * @param request 采编请求对象
     * @return 采编结果
     * @date 2017-9-14 上午9:23:59
     */
    @RequestMapping(value = {"/data/upload"}, method = RequestMethod.POST,
            consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public DataResult<List<ItemResponse>> uploadEditingData(@RequestBody EditingRequest request) {
    	if(logger.isDebugEnabled())
    		logger.debug("WorkStationController uploadEditingData");
        
        DataResult<List<ItemResponse>> result = new DataResult<List<ItemResponse>>();
        SysUser user = ECachePlugin.get(request.getSzUserId());
        if(user == null)
        {  
	        result.addError("非法提交"); 
	      	if(logger.isDebugEnabled())
	    		logger.debug("WorkStationController ##################  非法提交");
        }else
        {
        	result.addOK("", libraryService.doEdittingLabels(request, user)); 
        } 
        return result;
    }


    /**
     * 有问题 ！！！！！！！
     * 
     * @param books  采编成功图书信息
     * @param worker 采编人员
     */
    private void saveEditingLog(List<SysBook> books, SysUser worker) {
        if (books != null && books.size() != 0) {
            for (SysBook book : books
                    ) {
                //保存日志
                EditingLog entity = new EditingLog();
                entity.setBook_id(book.getBarcode());
                entity.setRFID(book.getRfid()); 
                entity.setCreate_by(worker.getId());
                entity.setUpdate_by(worker.getId());
                editingLogService.insert(entity);
            }
        }

    }


    /**
     * .
     * 图书查询(只查询本地信息足够)
     *
     * @param id 查询图书ID
     * @return 查询结果
     */
    @RequestMapping(value = {"/data/searchbook/{id}"}, method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public DataResult<List<ItemResponse>> searchBook(@PathVariable("id") String id) {
        System.out.print("RWorkStationController searchBook /n");
        DataResult<List<ItemResponse>> result = new DataResult<List<ItemResponse>>();
        List<ItemResponse> list = new ArrayList<ItemResponse>();
        ItemResponse item = new ItemResponse();  
        SysBook sysBook = bookInfoService.selectBookByRfid(id);
        try {
            if (sysBook == null) {
                item.setStatus(0);
                item.setMessage("无该图书");
                result.addError(id + item.getMessage());
            } else {
                //LibraryRequest<String> request = new LibraryRequest<String>();
                //List<SysBook> bookList = new ArrayList<SysBook>();
                //bookList.add(sysBook);
                //request.setData(sysBook.getBarcode());
                //item = libraryService.getBookInfo(request);
            	item.setBookName(sysBook.getBookname());
                item.setBarcode(sysBook.getBarcode());
                item.setRfid(sysBook.getRfid()); 
                list.add(item);
                result.addOK("", list); 
            }
        } catch (Exception e) {
        	logger.error("查询失败: " + e.getMessage());
            result.addError("查询失败");
            return result;
        }
        return result;

    }
    
    /***
     * 查询图书
     * @param id
     * @return
     * @date 2018年5月15日 下午3:15:40
     */
    @RequestMapping(value = {"/book/{id}"}, method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public DataResult<ItemResponse> getBook(@PathVariable("id") String id) {
        if (logger.isDebugEnabled()) {
        	logger.debug("getBook id: " + id);
        }
        DataResult<ItemResponse> result = new DataResult<ItemResponse>();
        ItemResponse item = new ItemResponse();
        try {
            SysBookVo sBook = bookInfoService.selectBookByRfid(id);
            if (null != sBook) { 
            	item = new ItemResponse();
            	item.setStatus(1); 
                item.setBookName(sBook.getBookname());
                item.setBarcode(sBook.getBarcode());
                item.setRfid(sBook.getRfid());
                if (item.getStatus() == 0) {
                    result.addError(item.getMessage());
                } else {
                    result.addOK("", item);
                }
            } else {
                item.setStatus(0);
                item.setMessage("无该图书");
                result.addError(item.getMessage());
            }
        } catch (Exception ex) {
        	logger.error("查询图书信息异常：" + ex.getMessage());
            item.setStatus(0);
            item.setMessage("查询异常");
            result.addError(item.getMessage());
        }
        return result;
    }


    /**
     * .
     * 借阅
     *
     * @param request 借阅请求
     * @return 借阅结果
     */
    @RequestMapping(value = {"/eslibrary/borrow"}, method = RequestMethod.POST,
            consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public DataResult<List<CheckOutResponse>> borrow(@RequestBody LibraryRequest<String[]> request) {
    	if(logger.isDebugEnabled())
    		logger.debug("RWorkStationController Borrow selectBookByRfid....");
        String[] barcodeList = selectBookByRfid(request.getData());
   
    	if(logger.isDebugEnabled())
    		logger.debug("RWorkStationController Borrow getReaderByRfid....");
        request.setData(barcodeList);
        SysReader sysReader = getReaderByRfid(request.getSzUserId());
      	if(logger.isDebugEnabled())
    		logger.debug("RWorkStationController Borrow doCheckout....");
        DataResult<List<CheckOutResponse>> result = doCheckout(request, sysReader);
        return result;
    }


    /**
     * .
     * 归还
     *
     * @param request 图书馆邮箱
     * @return 归还结果
     */
    @RequestMapping(value = {"/eslibrary/return"}, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public DataResult<List<CheckInResponse>> checkIn(@RequestBody LibraryRequest<String[]> request) {
        System.out.print("RWorkStationController checkin");
        String[] barcodeList = selectBookByRfid(request.getData());
        request.setData(barcodeList);
        DataResult<List<CheckInResponse>> result = doCheckIn(request);

        return result;
    }


    /***
     * 续借
     * @param request 续借请求
     * @return LibraryRequest
     */

    @RequestMapping(value = {"/eslibrary/renew"}, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public DataResult<List<CheckOutResponse>> renew(@RequestBody LibraryRequest<String[]> request) {
        System.out.print("RWorkStationController Renew");
        DataResult<List<CheckOutResponse>> result = new DataResult<List<CheckOutResponse>>();
        String[] barcodeList = selectBookByRfid(request.getData());
        SysReader sysReader = getReaderByRfid(request.getSzUserId());
        request.setData(barcodeList);
        result = doRenew(request, sysReader);
        return result;
    }
    
    /****
     * 解除绑定请求Action
     * @param request 请求对象
     * @return
     * @date 2018年5月14日 下午4:45:51
     */
    @RequestMapping(value = {"/untieLabels"}, method = RequestMethod.POST, 
    		produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public DataResult<List<ItemResponse>> doUntieLabels(@RequestBody LibraryRequest<String[]> request) {
        DataResult<List<ItemResponse>> result = new DataResult<List<ItemResponse>>();  
        List<ItemResponse> list = libraryService.doUntieLabels(request);
        result.addOK("", list);  
        return result;
    }


    /**
     * 采编上传执行
     *
     * @param bookList 采编图书
     * @param worker   采编人员
     * @return 采编结果
     */
    @Deprecated
    private DataResult<List<ItemResponse>> doUploadEditingData(List<SysBook> bookList, SysUser worker) {
        DataResult<List<ItemResponse>> result = new DataResult<List<ItemResponse>>();
        List<ItemResponse> list = new ArrayList<ItemResponse>();
        List<SysBook> uploadBooks = new ArrayList<SysBook>();
        ItemResponse item = null; 
        if (bookList == null || bookList.size() == 0) {
            result.addError("无上传信息");
          	if(logger.isDebugEnabled())
    	    		logger.debug("WorkStationController ##################  无上传信息"); 
        } else {
            for (SysBook book : bookList) {
                item = new ItemResponse(); 
                logger.info("barcode" + book.getBarcode());
                item.setBarcode(book.getBarcode());
                item.setRfid(book.getRfid()); 
                
                
                book.setUpdate_date(new Timestamp(System.currentTimeMillis()));
                try {
                    SysBook sbook = bookInfoService.selectBookByRfid(book.getRfid());
                    //已经存在的将不进行保存数据
                    if (sbook == null) { 
                        //todo
                        book.setCreate_by(worker.getId());
                        book.setUpdate_by(worker.getId());;
                        bookInfoService.insert(book);
                        //添加到采编成功列表
                        uploadBooks.add(book);
                    } else { //存在则更新
                    	book.setBarcode(book.getBarcode());
                    	book.setUpdate_by(worker.getId());;
                        //更新图书信息
                        bookInfoService.updateByIdSelective(book);
                        uploadBooks.add(book); 
                    }
                    item.addOK("上传数据成功");
                    list.add(item);
                } catch (Exception ex) {
                	logger.error("上传数据失败: " + ex.getMessage());
                    item.addError("上传数据失败");
                    list.add(item);
                }
            }
            result.addOK("", list);
        }
        saveEditingLog(uploadBooks, worker);
        return result;
    }


    /**
     * .
     * 借阅执行
     *
     * @param request 借阅请求
     * @param reader  读者信息
     * @return result
     */
    private DataResult<List<CheckOutResponse>> doCheckout(LibraryRequest<String[]> request, SysReader reader) {
        DataResult<List<CheckOutResponse>> result = new DataResult<List<CheckOutResponse>>();
        if (reader == null) {
            result.addError("读者信息不正确");
        } else if (request.getData() == null || request.getData().length == 0)  {
            result.addError("查无此书");
        } else {
            request.setSzUserId(reader.getCampusCardNum());
            List<CheckOutResponse> checkOutResponses = libraryService.doCheckout(request);
            result.addOK("", checkOutResponses);
            sysRecordService.saveRecord(RecordType.BORROW, checkOutResponses, reader);
        }

        return result;
    }


    /**
     * .
     * 归还执行
     *
     * @param request 归还请求
     * @return result
     */
    private DataResult<List<CheckInResponse>> doCheckIn(LibraryRequest<String[]> request) {
        DataResult<List<CheckInResponse>> result = new DataResult<List<CheckInResponse>>();
        if (request.getData() == null || request.getData().length == 0) {
            result.addError("查无此书");
        } else {
            List<CheckInResponse> checkInResponse = libraryService.doCheckin(request);
            result.addOK("", checkInResponse);
            sysRecordService.saveRecord(RecordType.RETURN, checkInResponse);
        }
        return result;
    }


    /**
     * .
     * 续借执行
     *
     * @param request 续借请求
     * @param reader  续借读者信息
     * @return result
     */
    private DataResult<List<CheckOutResponse>> doRenew(LibraryRequest<String[]> request, SysReader reader) {
        DataResult<List<CheckOutResponse>> result = new DataResult<List<CheckOutResponse>>();
        if (reader == null) {
            result.addError("读者信息不正确");
        } else if (request.getData() == null || request.getData().length == 0) {
            result.addError("查无此书");
        } else {
            request.setSzUserId(reader.getCampusCardNum());
            List<CheckOutResponse> checkOutResponses = libraryService.doRenew(request);
            result.addOK("", checkOutResponses);
            sysRecordService.saveRecord(RecordType.REVEW, checkOutResponses, reader);
        }

        return result;
    }

    /**
     * .
     * 通过rfid获取完整图书信息
     *
     * @param rfidList 请求图书列表
     * @return barcodeList
     */
    private String[] selectBookByRfid(String[] rfidList) {
        List<String> list = new ArrayList<String>();
        for (String rfid : rfidList) {
            SysBookVo sysBookVo = bookInfoService.selectBookByRfid(rfid);
            if (sysBookVo != null) {
            	list.add(sysBookVo.getBarcode());
            }
        }
        return list.toArray(new String[list.size()]);
    }

    /**
     * .
     * 通过RFID获取完整读者信息
     *
     * @param rfid 读者RFID号
     * @return reader
     */
    private SysReader getReaderByRfid(String rfid) {
        SysReader reader = new SysReader();
        reader.setRfidCardNum(rfid);
        reader = sysReaderService.queryOne(reader);
        return reader;
    }


}
